﻿using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine.SceneManagement;
using UnityEngine;

/// <summary>
/// 游戏状态控制器 -- 状态模式
/// </summary>
public class SceneStateController
{
    private ISceneState mState;
    private AsyncOperation mAO;
    private bool mIsRunStart = false;
    
    /// <summary>
    /// 设置状态
    /// </summary>
    /// <param name="state"></param>
    /// <param name="isLoadScene"></param>
    public void SetState(ISceneState state,bool isLoadScene=true)
    {
        if (mState != null)
        {
            mState.StateEnd();// 让上一个场景状态做一下清理工作
        }
        
        // 设置状态
        mState = state;
        
        // 判断场景是否加载
        if (isLoadScene)
        {
            mAO = SceneManager.LoadSceneAsync(mState.SceneName);
            mIsRunStart = false;
        } 
        else
        {
            mState.StateStart();
            mIsRunStart = true;
        }
        
    }

    public void StateUpdate()
    {
        // 场景不存在或已销毁
        if (mAO != null && mAO.isDone == false) return;
        
        // 状态开始
        if (mIsRunStart == false && mAO != null && mAO.isDone == true)
        {
            mState.StateStart();
            mIsRunStart = true;
        }
        
        // 状态更新
        if (mState != null)
        {
            mState.StateUpdate();
        }
    }
}
